<template>
  <div class="payment-container">
    <!-- 支付宝标题栏 -->
    <div class="payment-header">
      <div class="alipay-logo">支</div>
      <div class="header-text">收银台</div>
    </div>

    <!-- 订单信息 -->
    <div class="order-info">
      <div class="product-list">
        <table class="order-table">
          <thead>
            <tr>
              <th>商品名</th>
              <th>尺码</th>
              <th>单价</th>
              <th>数量</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in orderDetail?.orderItems" :key="index">
              <td class="name-cell">
                <div class="product-name">{{ item.productName }}</div>
                <img
                  :src="getImageUrl(item.productImage)"
                  alt="商品图片"
                  class="product-image"
                  @error="handleImageError"
                />
              </td>
              <td class="size-cell">{{ item.size }}</td>
              <td class="price-cell">
                ¥{{
                  ((item.totalPrice || 0) / (item.quantity || 1)).toFixed(2)
                }}
              </td>
              <td class="quantity-cell">{{ item.quantity }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="total-amount">
        订单金额
        <span class="amount">{{ orderDetail?.totalAmount?.toFixed(2) }}</span>
        元
      </div>
    </div>

    <!-- 新的两栏布局 -->
    <div class="payment-bottom">
      <!-- 左侧支付卡片 -->
      <a-card class="payment-card" :bordered="false" hoverable>
        <div class="payment-amount">
          支付 {{ orderDetail?.totalAmount?.toFixed(2) || "0.00" }} 元
        </div>

        <a-divider />

        <!-- 密码输入部分 -->
        <div class="password-section">
          <div class="security-notice">
            <span class="success-icon">✓</span> 安全设置检测成功！
          </div>
          <div class="password-input">
            <label>支付宝支付密码：</label>
            <div class="password-boxes" @click="focusMainInput">
              <input
                type="text"
                v-model="password"
                class="hidden-input"
                maxlength="6"
                inputmode="numeric"
                pattern="[0-9]*"
                @input="handleInput"
                @blur="handleBlur"
                ref="mainInput"
              />
              <div
                v-for="(digit, index) in 6"
                :key="index"
                class="password-box"
              >
                <span v-if="password[index]" class="password-dot"></span>
              </div>
            </div>
            <a href="#" class="forgot-password">忘记密码？</a>
          </div>
          <a-button
            type="primary"
            class="confirm-button"
            :loading="submitting"
            :disabled="password.length !== 6"
            @click="handlePayment"
          >
            确认支付
          </a-button>
        </div>
      </a-card>

      <!-- 右侧二维码卡片 -->
      <a-card class="qrcode-card" :bordered="false" hoverable>
        <div class="qrcode-content">
          <a-card-meta
            title="使用支付宝APP扫码付款"
            description="打开支付宝扫一扫"
          />
          <div class="qrcode-wrapper">
            <img src="@/picture/pay/QRcode.png" alt="支付宝二维码" />
          </div>
        </div>
      </a-card>
    </div>

    <!-- 添加支付成功弹窗 -->
    <a-modal
      v-model:visible="showSuccessModal"
      :closable="false"
      :maskClosable="false"
      :footer="null"
      width="400px"
      class="success-modal"
    >
      <div class="success-content">
        <div class="success-icon">✓</div>
        <div class="success-title">支付成功</div>
        <div class="success-message">
          订单支付成功，{{ countdown }}秒后跳转到订单详情页...
        </div>
      </div>
    </a-modal>
  </div>
</template>

<style scoped>
.payment-container {
  padding: 20px;
  background: #fff;
  font-size: 16px;
  font-weight: 500;
}

.payment-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #e8e8e8;
  padding-bottom: 10px;
}

.alipay-logo {
  color: #1677ff;
  font-size: 30px;
  margin-right: 10px;
  font-weight: bold;
}

.header-text {
  font-size: 22px;
  font-weight: bold;
}

.order-info {
  margin-bottom: 30px;
}

.merchant-info {
  color: #666;
  margin-bottom: 10px;
}

.product-list {
  margin: 20px 0;
}

.order-table {
  width: 100%;
  border-collapse: collapse;
}

.order-table th {
  height: 40px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
  color: #666;
  font-weight: 600;
  text-align: left;
  padding: 12px 16px;
  font-size: 16px;
}

.order-table td {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 16px;
}

.name-cell {
  max-width: 400px;
}

.product-info {
  display: flex;
  align-items: center;
}

.product-name {
  margin-right: 20px;
  color: #333;
  font-weight: 500;
  font-size: 16px;
}

.product-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
}

.price-cell {
  color: #ff4000;
  font-weight: 600;
  font-size: 18px;
}

.size-cell,
.quantity-cell {
  text-align: center;
  font-weight: 500;
  font-size: 16px;
}

.total-amount {
  text-align: right;
  padding: 20px 0;
  font-size: 18px;
  border-top: 1px solid #f0f0f0;
  font-weight: 500;
}

.amount {
  color: #ff6700;
  font-size: 28px;
  font-weight: bold;
  margin: 0 5px;
}

.payment-amount {
  font-size: 24px;
  font-weight: bold;
  color: #ff4000;
  text-align: center;
  margin: 20px 0;
}

.payment-methods {
  margin-bottom: 30px;
}

.bank-card-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  border: 2px solid #1677ff;
  border-radius: 4px;
  margin: 20px 0;
}

.other-methods {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.qr-button {
  position: relative;
}

.qr-code {
  position: absolute;
  right: 0;
  top: 100%;
  width: 100px;
  height: 100px;
  margin-top: 10px;
}

.password-section {
  max-width: none;
}

.security-notice {
  color: #52c41a;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 500;
}

.success-icon {
  margin-right: 5px;
}

.password-input {
  display: flex;
  align-items: center;
  margin: 20px 0;
  font-size: 16px;
}

.password-input label {
  font-weight: 600;
  margin-right: 10px;
  font-size: 16px;
}

.password-boxes {
  position: relative;
  display: flex;
  gap: 5px;
}

.password-box {
  width: 40px;
  height: 40px;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  cursor: text;
}

.forgot-password {
  margin-left: 10px;
  color: #1677ff;
  text-decoration: none;
}

.confirm-button {
  width: 100%;
  height: 45px;
  margin-top: 20px;
  font-size: 18px;
  font-weight: bold;
}

.payment-bottom {
  display: flex;
  gap: 20px;
  margin-top: 20px;
}

.payment-card {
  flex: 7;
  transition: all 0.3s ease;
}

.qrcode-card {
  flex: 3;
  transition: all 0.3s ease;
}

.payment-card:hover,
.qrcode-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.qr-code {
  width: 100px;
  height: 100px;
  object-fit: contain;
  margin: 0 auto;
  display: block;
}

:deep(.ant-card-meta-title) {
  font-size: 14px;
  color: #333;
  text-align: center;
}

:deep(.ant-card-meta-description) {
  font-size: 12px;
  color: #666;
  text-align: center;
}

:deep(.ant-card-cover) {
  padding: 20px;
}

.qrcode-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
}

.qrcode-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-grow: 1;
  padding: 20px 0;
}

.qrcode-wrapper img {
  width: 180px;
  height: 180px;
  object-fit: contain;
}

.hidden-input {
  position: absolute;
  opacity: 0;
  width: 1px;
  height: 1px;
}

.password-dot {
  width: 10px;
  height: 10px;
  background-color: #000;
  border-radius: 50%;
  display: inline-block;
}

/* 添加loading状态样式 */
.confirm-button.ant-btn-loading {
  opacity: 0.8;
  cursor: not-allowed;
}

/* 添加支付成功弹窗样式 */
.success-modal {
  text-align: center;
}

.success-content {
  padding: 20px;
}

.success-icon {
  font-size: 48px;
  color: #52c41a;
  margin-bottom: 16px;
}

.success-title {
  font-size: 28px;
  color: #333;
  margin-bottom: 16px;
  font-weight: bold;
}

.success-message {
  font-size: 18px;
  color: #666;
  font-weight: 500;
}

:deep(.ant-modal-content) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.ant-modal-body) {
  padding: 32px;
}
</style>

<script setup lang="ts">
/// <reference types="node" />

import { ref, onMounted, onUnmounted } from "vue";
import { Card, Button, Divider, message } from "ant-design-vue";
import { useRoute, useRouter } from "vue-router";
import {
  getOrderDetailUsingPost,
  payOrderUsingPost,
} from "@/api/orderController";
import type API from "@/api";

const route = useRoute();
const router = useRouter();
const password = ref("");
const mainInput = ref<HTMLInputElement | null>(null);
const orderDetail = ref<API.OrderDetailVO>();
const submitting = ref(false);
const showSuccessModal = ref(false);
const countdown = ref(3);
let timer: number | null = null;

// 加载订单详情
const loadOrderDetail = async () => {
  try {
    const orderId = route.query.orderId;
    if (!orderId) {
      message.error("订单ID无效");
      return;
    }

    const res = await getOrderDetailUsingPost({ id: Number(orderId) });
    if (res.data?.code === 0 && res.data.data) {
      orderDetail.value = res.data.data;
    } else {
      message.error("获取订单详情失败");
    }
  } catch (error) {
    console.error("获取订单详情失败:", error);
    message.error("获取订单详情失败");
  }
};

// 处理支付
const handlePayment = async () => {
  if (password.value.length !== 6) {
    message.warning("请输入6位支付密码");
    return;
  }

  if (submitting.value) return;

  try {
    submitting.value = true;

    // 使用订单ID作为参数，不需要额外的支付密码参数
    const payRequest = {
      id: Number(route.query.orderId),
    };

    console.log("支付请求参数:", payRequest);

    const res = await payOrderUsingPost(payRequest);

    console.log("支付响应:", res.data);

    if (res.data?.code === 0) {
      showSuccessModal.value = true;
      startCountdown();
    } else {
      message.error(res.data?.message || "支付失败");
    }
  } catch (error) {
    console.error("支付失败:", error);
    message.error("支付失败，请稍后重试");
  } finally {
    submitting.value = false;
  }
};

const handleInput = (event: Event) => {
  const input = event.target as HTMLInputElement;
  // 只允许数字输入
  password.value = input.value.replace(/[^0-9]/g, "");
};

const focusMainInput = () => {
  mainInput.value?.focus();
};

// 当输入框失去焦点时，立即重新获取焦点
const handleBlur = (event: FocusEvent) => {
  // 使用 setTimeout 确保在点击其他元素后仍然重新获得焦点
  setTimeout(() => {
    focusMainInput();
  }, 10);
};

// 添加图片处理函数
const getImageUrl = (imageName: string | undefined) => {
  if (!imageName) {
    return "https://graduationdesign-1325357602.cos.ap-guangzhou.myqcloud.com/default.png";
  }
  return imageName.trim();
};

// 添加图片加载失败处理函数
const handleImageError = (e: Event) => {
  const img = e.target as HTMLImageElement;
  img.src =
    "https://graduationdesign-1325357602.cos.ap-guangzhou.myqcloud.com/default.png";
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 3;
  timer = window.setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      window.clearInterval(timer!);
      router.push(`/order/${route.query.orderId}`);
    }
  }, 1000);
};

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    window.clearInterval(timer);
  }
});

// 页面加载时自动聚焦
onMounted(() => {
  loadOrderDetail();
  focusMainInput();
});
</script>
